<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="凭证类型" prop="evidenceType">
        <el-select v-model="queryParams.evidenceType" placeholder="请选择凭证类型" clearable>
          <el-option v-for="dict in dict.type.evidence_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="单据" prop="receipts">
        <el-input v-model="queryParams.receipts" placeholder="请输入单据" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="账套外键" prop="accountSetId">
        <el-input v-model="queryParams.accountSetId" placeholder="请输入账套外键" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="租户Id" prop="tenantId">
        <el-input v-model="queryParams.tenantId" placeholder="请输入租户Id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="账套Id" prop="accountId">
        <el-input v-model="queryParams.accountId" placeholder="请输入账套Id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['evidence:evidence:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['evidence:evidence:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['evidence:evidence:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['evidence:evidence:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="evidenceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="创建日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="凭证类型" align="center" prop="evidenceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.evidence_type" :value="scope.row.evidenceType" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="单据" align="center" prop="receipts" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.receipts" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账套外键" align="center" prop="accountSetId" />
      <el-table-column label="租户Id" align="center" prop="tenantId" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['evidence:evidence:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-ic
          on-delete" @click="handleDelete(scope.row)" v-hasPermi="['evidence:evidence:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改凭证列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="凭证类型" prop="evidenceType">
          <el-select v-model="form.evidenceType" placeholder="请选择凭证类型">
            <el-option v-for="dict in dict.type.evidence_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTevi">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteTevi">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="plus" @click="handlemodel">保存为模板</el-button>
          </el-col>
        </el-row>
        <el-table :data="tbEviList" :row-class-name="rowtEviIndex" @selection-change="handleSelectionChangeTbEvi"
          ref="tEvi">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="index" />
          <el-table-column label="摘要" prop="digest">
            <template slot-scope="scope">
              <el-input v-model="scope.row.digest" placeholder="请输入摘要" />
            </template>
          </el-table-column>
          <el-table-column label="会计科目" prop="accountingSubject">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.accountingSubject" placeholder="请输入会计科目" /> -->
              <el-select v-model="scope.row.accountingSubject" filterable placeholder="请选择">
                <el-option v-for="item in subjects" :key="item.id" :label="item.subjectName"
                  :value="item.subjectName"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="借方金额" prop="debtorMoney">
            <template slot-scope="scope">
              <el-input v-model="scope.row.debtorMoney" @change="cleanCred(scope.row)" @input="updateTotals"
                placeholder="请输入借方金额" />
            </template>
          </el-table-column>
          <el-table-column label="贷方金额" prop="creditorMoney">
            <template slot-scope="scope">
              <el-input v-model="scope.row.creditorMoney" @change="cleanDebt(scope.row)" @input="updateTotals"
                placeholder="请输入贷方金额" />
            </template>
          </el-table-column>
          <p>借方总额: {{ totalDebtor }}</p>
          <p>贷方总额: {{ totalCreditor }}</p>
          <p v-if="!isBalanced" style="color: red;">借贷不平衡</p>
        </el-table>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="单据" prop="receipts">
          <image-upload v-model="form.receipts" />
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEvidence, getEvidence, delEvidence, addEvidence, updateEvidence } from "@/api/evidence/evidence";
import { listEvi, getEvi, delEvi, addEvi, updateEvi, listById, addModel } from "@/api/evidence/evi";
import {
  listSubject,
  getSubject,
  delSubject,
  addSubject,
  updateSubject,
  selectListBySubject
} from "@/api/subject/subject";
import { parseTime } from "@/utils/vctgo";

export default {
  name: "Evidence",
  dicts: ['evidence_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 凭证列表表格数据
      evidenceList: [],
      eviList: [],
      evis: [],
      tbEviList: [],

      checkedtEvi: [],

      subjects: [],

      eviId: {},

      totalDebtor: 0,
      totalCreditor: 0,

      obj: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        evidenceType: null,
        receipts: null,
        accountSetId: null,
        tenantId: null,
        accountId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.selectSubject();
  },
  computed: {
    isBalanced() {
      return this.totalDebtor === this.totalCreditor;
    },
  },
  methods: {

    /**借贷平衡校验 */
    updateTotals() {
      this.totalDebtor = this.tableData.reduce((acc, row) => acc + parseFloat(row.debtorMoney || 0), 0);
      this.totalCreditor = this.tableData.reduce((acc, row) => acc + parseFloat(row.creditorMoney || 0), 0);
    },
    /**添加科目 */
    handleAddSubject() {

    },

    /**会计科目下拉框 */
    selectSubject() {
      debugger;
      selectListBySubject().then(response => {
        this.subjects = response.data;
      });
    },
    /**清空贷方金额 */
    cleanCred(data) {
      debugger;
      console.log(data.creditorMoney);
      data.creditorMoney = "";
      console.log(data.creditorMoney);
    },
    /**清空借方金额 */
    cleanDebt(data) {
      console.log(data.debtorMoney);
      data.debtorMoney = "";
      console.log(data.debtorMoney);
    },
    /** 查询凭证列表列表 */
    getList() {
      this.loading = true;
      listEvidence(this.queryParams).then(response => {
        this.evidenceList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        evidenceType: null,
        remark: null,
        receipts: null,
        updateTime: null,
        accountSetId: null,
        tenantId: null,
        accountId: null
      };
      this.tbEviList = [];
      this.resetForm("form");
    },
    // 添加凭证按钮
    handleAddTevi() {

      let obj = {};
      obj.digest = "";
      obj.accountingSubject = "";
      obj.debtorMoney = "";
      obj.creditorMoney = "";
      this.tbEviList.push(obj);
    },
    /**凭证删除按钮 */
    handleDeleteTevi() {
      if (this.checkedtEvi.length === 0) {
        this.$message.error("请先选择要删除的凭证数据");
      } else {
        const evis = this.tbEviList;
        const checkedtEvis = this.checkedtEvi;
        this.tbEviList = evis.filter(function (item) {
          return checkedtEvis.indexOf(item.index) === -1;
        });
      }
    },
    /**保存为模板 */
    handlemodel() {

      this.form.tbEviList = this.tbEviList;
      console.log(this.form);

      addModel(this.form).then(response => {
        this.$message({
          message: "保存成功",
          type: "success"
        });
      });
    },
    rowtEviIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    handleSelectionChangeTbEvi(selection) {
      this.checkedtEvi = selection.map(item => item.index);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加凭证列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.eviId.evidentId = id;
      getEvidence(id).then(response => {

        listById(id).then(response => {
          console.log(response.data);
          this.tbEviList = response.data;
        });
        this.form = response.data;
        // console.log(response.data);


        this.open = true;
        this.title = "修改凭证列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.tbEviList = this.tbEviList;
          if (this.form.id != null) {
            updateEvidence(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEvidence(this.form).then(response => {
              console.log(this.form.tbEviList);

              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除当前凭证列表数据项？').then(function () {
        return delEvidence(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('evidence/evidence/export', {
        ...this.queryParams
      }, `凭证列表_${parseTime(new Date().getTime(), '{y}-{m}-{d}')}.xlsx`)
    }
  }
};
</script>
